//
//  codeViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/16.
//

#import "CodeViewController.h"
#import "PayPassWordViewController.h"
#import "PassWordViewController.h"
#import "FaceIDViewController.h"

@interface CodeViewController ()
@property(nonatomic,strong)TKLtextFiled * codeFiled;
@property (strong, nonatomic)  UIButton *verticodeBtn;
@property(nonatomic,strong)UIView * messageView;

@property(nonatomic,strong)dispatch_source_t _sometimer;
@property(nonatomic,strong)NSString * authorizationCode;//授权码
@property (assign,nonatomic) NSInteger BiometryTypeNumber;
@property (strong,nonatomic) NSString * BiometryTypeStr;
@property(nonatomic,strong)NSString * userUID;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation CodeViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:backBtn];

//    [self getVerticode:self.verticodeBtn];
    
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = Wcolor;
    
//    if ([self.pushPath isEqualToString:@"newForget"]||[self.pushPath isEqualToString:@"oldForget"]) {
        UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [self.view addSubview:backBtn];
        
        
//        //是否有返回
//        TKLlable * navTit = [TKLlable labelWithFrame:CGRectMake(kWidth/2-60, kStatusBarHeight+5, 120, 20) text:@"找回登录密码" textColor:Bcolor font:Font_6(16) textAlignment:Textcenter backgroundColor:Ccolor];
//        [self.view addSubview:navTit];
//    }
//
    
    
    // Do any additional setup after loading the view.
    [self  loadUIView];
    
    
    if ([self.pushPath containsString:@"cer"]) {
        //证书相关验证码
        [self getCerCodeUrl];
     
    }else{
        //密码相关验证码
        [self getVerCodeUrl];
    }
    

  //登录密码相关验证码
    
    
    
    // Do any additional setup after loading the view.
}



-(void)loadUIView{
    
    TKLlable * lognLab = [TKLlable labelWithFrame:CGRectMake(30, 100, 50, 30) text:@"登录" textColor:JhColor(51, 51, 51) font:Font_6(24) textAlignment:Textleft backgroundColor:Ccolor];
    
    lognLab.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];
    [self.view addSubview:lognLab];
    
    TKLlable * messLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+20, kWidth-60, 20) text:@"您在资金系统预留的手机号为:" textColor:JhColor(181, 181, 181) font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];

       [self.view addSubview:messLab];
  
    TKLlable * phoneLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(messLab.frame)+5, kWidth-60, 16) text:@"" textColor:JhColor(181, 181, 181) font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];

       [self.view addSubview:phoneLab];
    
    
    NSString *numberString = [self.phoneNumberStr stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    phoneLab.text = [NSString stringWithFormat:@"%@",numberString];
    
    
    
    
    self.codeFiled = [TKLtextFiled FiledWithFrame:CGRectMake(30, 175+30,kWidth-160 , 20) text:@"请输入验证码" textColor:JhColor(51, 51, 51) font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    self.codeFiled.keyboardType = UIKeyboardTypeNumberPad;
    [self.codeFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.codeFiled];
    
    self.verticodeBtn = [UIButton createBtnFrame:CGRectMake(CGRectGetMaxX(self.codeFiled.frame)+10, CGRectGetMaxY(lognLab.frame)+75, 100, 20) title:@"" bgImageName:@"" action:^(UIButton *button) {
        ;
        self.verticodeBtn.userInteractionEnabled = NO;
        [self.view endEditing:YES];
        
        
        [self starTime];

        if ([self.pushPath containsString:@"cer"]) {
            //证书相关验证码
            [self getCerCodeUrl];
         
        }else{
            //密码相关验证码
            [self getVerCodeUrl];
        }
        
    
        
    }];
    [self.verticodeBtn setTitleColor:JhColor(153, 153, 153) forState:UIControlStateNormal];
    [self.view addSubview:self.verticodeBtn];
    
    
    self.verticodeBtn.userInteractionEnabled = NO;

    
    
    [self starTime];
    
    self.messageView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.codeFiled.frame)+10, kWidth-60, 1)];
    self.messageView.backgroundColor = JhColor(153, 153, 153);
    [self.view addSubview:self.messageView];
    
    //next
    UIButton * nextBtn = [UIButton createBtnFrame:CGRectMake(30, CGRectGetMaxY(self.messageView.frame)+20, kWidth-60, 44) title:@"下一步" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
        self.codeFiled.text = [self.codeFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];

        if (self.codeFiled.text.length == 6) {

            if ([self.pushPath containsString:@"Forget"] ) {
  
               //验证码校验
              
                [self autjorizationVerifyUrl];
//                PassWordViewController *  passVC  =[[PassWordViewController alloc]init];
//                passVC.modalPresentationStyle = 0;
//                passVC.userName = self.userName;
//                passVC.pushPath = self.pushPath;
//                passVC.verifyCode = self.codeFiled.text;
//                passVC.phoneNumber = self.phoneNumberStr;
//                [self presentViewController:passVC animated:YES completion:nil];
                
            }else if([self.pushPath containsString:@"cer"]){
    
                
                //验证证书验证码
                [self autjorizationCerVerifyUrl];
              
  
            }


        }else{
            [MBProgressHUD showMessage:@"验证码格式不正确" toView:self.view];


        }
        
      
   
        
    }];
//    nextBtn
    nextBtn.backgroundColor = JhColor(21, 126, 251);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = 5;
    [self.view addSubview:nextBtn];
    
//    TKLlable * phoneChangeSign = [TKLlable labelWithFrame:CGRectMake(20, CGRectGetMaxY(nextBtn.frame)+20, kWidth-40, 20) text:@"若手机号有变请联系管理员" textColor:JhColor(102, 102, 102) font:Font_6(14) textAlignment:Textcenter backgroundColor:Ccolor];
//    [self.view addSubview:phoneChangeSign];
    
    
    
    
}



- (void)starTime{
    
    
    
    NSTimeInterval seconds =60;
    NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds];// 最后期限
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    self._sometimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
    dispatch_source_set_timer(self._sometimer, dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0);// 每秒执行一次
    dispatch_source_set_event_handler(self._sometimer, ^{
        int interval = [endTime timeIntervalSinceNow];
        if(interval >0) {// 更新倒计时
            NSString *timeStr = [NSString stringWithFormat:@"重新发送%d秒", interval];
            dispatch_async(dispatch_get_main_queue(), ^{

                [self.verticodeBtn setTitle:timeStr forState:UIControlStateNormal];
                [self.verticodeBtn setTitleColor:JhColor(153, 153, 153) forState:UIControlStateNormal];
                self.verticodeBtn.userInteractionEnabled = NO;
            });
        }else{
            // 倒计时结束，关闭
            dispatch_source_cancel(self._sometimer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.verticodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
             
                [self.verticodeBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                self.verticodeBtn.userInteractionEnabled = YES;
            });
        }
    });
    dispatch_resume(self._sometimer);
    
    

}
//证书验证码
-(void)getCerCodeUrl{
    
    [NetRequestClass NetRequestGETWithRequestURL:kCerMessage_Send_Api WithParameter:@{@"mobile":self.phoneNumberStr} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        if ([returnValue[@"code"] intValue] ==200) {
            [MBProgressHUD showMessage:@"验证码已发送" toView:self.view];
        }else{
            

            
            [MBProgressHUD  showMessage:@"验证码获取出错" toView:self.view];
        }
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            ;
        } WithFailureBlock:^{
            ;
        }];
    
   
    
    
}
-(void)getVerCodeUrl{
    

    
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kMessage_Send_Api WithString:self.phoneNumberStr WithReturnValeuBlock:^(id  _Nonnull returnValue) {
//            NSLog(@"%@",returnValue);
        
        if ([returnValue[@"code"] intValue] ==200) {
            [MBProgressHUD showMessage:@"验证码已发送" toView:self.view];
        }else{
            

            
            [MBProgressHUD  showMessage:@"验证码获取出错" toView:self.view];
        }
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            ;
        } WithFailureBlock:^{
            ;
        }];
    

    
}

-(void)autjorizationCerVerifyUrl{
    
    [NetRequestClass NetRequestGETWithRequestURL:kRestMessageCer_Send_Api WithParameter:@{@"mobile":self.phoneNumberStr,@"code":self.codeFiled.text} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        NSLog(@"%@",returnValue);
      
            if ([returnValue[@"code"] intValue]  ==200) {
            
                
                PayPassWordViewController * passVC  =[[PayPassWordViewController alloc]init];
                passVC.modalPresentationStyle = 0;
                passVC.userName = self.userName;
                passVC.phoneNuM = self.phoneNumberStr;
                passVC.pushPath = self.pushPath;
                passVC.codeStr = self.codeFiled.text;
                [self presentViewController:passVC animated:YES completion:nil];
            }else if([returnValue[@"code"] intValue] == 906){
                
                [MBProgressHUD showMessage:@"验证码错误" toView:self.view];
            }else{
                [MBProgressHUD showMessage:returnValue[@"msg"] toView:self.view];
            }
            
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            ;
        } WithFailureBlock:^{
            ;
        }];
    
}

//校验验证码
-(void)autjorizationVerifyUrl{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = NSLocalizedString(@"请稍等", @"HUD loading title");
    [NetRequestClass NetRequestGETWithRequestURL:kRestMessage_Send_Api WithParameter:@{@"code":self.codeFiled.text,@"mobile":self.phoneNumberStr} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        self.hud.hidden = YES;
        if ([returnValue[@"code"] intValue]  ==200) {
        
            
            PassWordViewController * passVC  =[[PassWordViewController alloc]init];
            passVC.modalPresentationStyle = 0;
            passVC.userName = self.userName;
            passVC.phoneNumber = self.phoneNumberStr;
            passVC.pushPath = self.pushPath;
            passVC.verifyCode = self.codeFiled.text;
            [self presentViewController:passVC animated:YES completion:nil];
        }else if([returnValue[@"code"] intValue] == 906){
            
            [MBProgressHUD showMessage:@"验证码错误" toView:self.view];
        }else{
            [MBProgressHUD showMessage:returnValue[@"msg"] toView:self.view];
        }
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            self.hud.hidden = YES;
        } WithFailureBlock:^{
            self.hud.hidden = YES;
        }];
    
    
}
-(void)getAuthorizationCodeUrlReply{
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kCertificate_RefreshCode_Api WithParameter:@{@"uid":self.userUID,@"username":self.userName} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
//        NSLog(@"%@",returnValue);

        if ([returnValue[@"code"] intValue] == 200) {

            NSString * getCodeStr = returnValue [@"data"];

            NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        
            [IMUser signUpWithUserName:[stand objectForKey:@"userName"] signCode:getCodeStr andCompleteBlock:^(int resultCode, IMUser *user) {
                
             
//                NSLog(@"%d %@",resultCode,user.username);
                if (resultCode == IM_ER_SUCCESS) {
//                    NSLog(@"注册成功");
                 
                    if (![IMCert hasCertWithUsername:user.username]) {
                  
                        PayPassWordViewController *payVC = [[PayPassWordViewController alloc]init];
                        payVC.user = user;
                        payVC.pushPath = self.pushPath;
                        payVC.userPhone = self.phoneNumberStr;
                        payVC.modalPresentationStyle = 0;
                        [self presentViewController:payVC animated:YES  completion:nil];
                        
                    }else{
                      
                  
                        
                    }

                }else{
                    NSLog(@"注册失败");
                    [MBProgressHUD showMessage:@"注册失败" toView:self.view];

                }
            }];
            
        
          
        }else{
            if ([returnValue[@"code"] intValue] == 999) {
                [MBProgressHUD showError:@"获取授权失败，请联系管理员" toView:self.view];
            }else{
                [MBProgressHUD showError:returnValue[@"msg"] toView:self.view];
            }
            
        }
        
        
       
        
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
        
            
            
            
            [MBProgressHUD showError:@"调取接口失败" toView:self.view];
        } WithFailureBlock:^{
            ;
        }];
    
    
}
- (void)textFieldDidChange:(UITextField *)textField{
   
    if (textField == self.codeFiled) {
        if (textField.text.length > 6) {
            self.codeFiled.text = [textField.text substringToIndex:6];
        }
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
